/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  SupervisionAddOwnerActivity.java   
 * @Package com.jiyi.activity.supervision   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-18 下午2:27:48   
 * @version V1.0     
 */
package com.jiyi.activity.supervision;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.weibao.CompanyBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.SupervisionOwnerEvent;
import com.jiyi.inteface.WebApi;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.SysUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: SupervisionAddOwnerActivity
 * @Description:TODO(纳入管辖)
 * @author: HYM
 * @date: 2017-10-18 下午2:27:48
 * 
 */
public class SupervisionAddOwnerActivity extends ActivityBase implements
		OnRefreshListener {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.tvAdd)
	TextView tvAdd;
	@BindView(R.id.mainList)
	RecyclerView mainList;
	private List<CompanyBean> dataList = new ArrayList<CompanyBean>();
	EmptyWrapper adapter;

	// 加载进度条
	Dialog dialog;
	LayoutInflater inflater;

	// 保存当前选择的id
	ArrayList<String> idsList = new ArrayList<String>();
	// 监管大队的id,name
	String supervision_id, supervision_name;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_supersivion_add_owner);
		ButterKnife.bind(this);
		init();
	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	private void init() {
		inflater = LayoutInflater.from(this);
		getIntentData();
		setTop();
		setAdapter();
		getData();
	}

	private void getIntentData() {
		supervision_id = getIntent().getStringExtra("supervision_id");
		supervision_name = getIntent().getStringExtra("supervision_name");
	}

	private void setTop() {
		tvTitle.setText("新增管辖");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("取消");
	}

	private void setAdapter() {
		// 设置布局管理器
		mainList.setLayoutManager(new LinearLayoutManager(this));
		mainList.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, null));
		// 初始化适配器
		CommonAdapter commonAdapter = new CommonAdapter<CompanyBean>(this,
				R.layout.item_supervision_owner_add, dataList) {
			@Override
			protected void convert(final ViewHolder holder,
					final CompanyBean t, final int position) {
				holder.setVisible(R.id.cbMove, true);
				holder.setChecked(R.id.cbMove, t.getIsCheck());
				holder.setText(R.id.tvOwnerPhone, t.getPhone());
				holder.setText(R.id.tvOwnerName, t.getName());
				holder.setOnClickListener(R.id.rlRoot, new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 获取当前对象是否选中
						boolean isCheck = t.getIsCheck();
						// 然后设置反值
						dataList.get(holder.getPosition()).setIsCheck(!isCheck);
						saveIds(t.getId());
						setCurrentNum();
						// 设置checkbox选中
						holder.setChecked(R.id.cbMove, t.getIsCheck());
					}
				});
			}
		};

		adapter = new EmptyWrapper(commonAdapter);
		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				mainList, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		// recycleview设置适配器
		mainList.setAdapter(adapter);
	}

	private void getData() {

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());

		VolleyRequest.StringRequestPost(this,
				WebApi.SUPERVISION_OWNER_ADD_LIST, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<CompanyBean> temp = new Gson().fromJson(
										data,
										new TypeToken<List<CompanyBean>>() {
										}.getType());
								dataList.clear();
								dataList.addAll(temp);
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});

	}

	@Override
	public void onRefresh() {
		getData();
	}

	/**
	 * @author: HYM
	 * @Title: allSelect
	 * @Description: TODO(全选按钮执行的方法) void
	 * @date: 2017-6-13
	 */
	void allSelect() {
		if (dataList.size() <= 0) {
			return;
		}

		boolean isAll = getIsAll();

		// 遍历全部数据，如果是需要全选则添加，如果需要反选 则删减
		for (int i = 0; i < dataList.size(); i++) {
			dataList.get(i).setIsCheck(isAll);
			if (isAll) {
				if (!idsList.contains(dataList.get(i).getId())) {
					idsList.add(dataList.get(i).getId());
				}
			} else {
				if (idsList.contains(dataList.get(i).getId())) {
					idsList.remove(dataList.get(i).getId());
				}
			}
		}
		adapter.notifyDataSetChanged();
		setCurrentNum();
	}

	void setCurrentNum() {
		if (idsList.size() > 0) {
			tvAdd.setText("纳入管辖(" + idsList.size() + ")");
			tvAdd.setEnabled(true);
		} else {
			tvAdd.setText("纳入管辖");
			tvAdd.setEnabled(false);
		}

		Log.e("cur  ", idsList.toString());
	}

	/**
	 * @author: HYM
	 * @Title: getIsAll
	 * @Description: TODO(判断下次是否应该全选)
	 * @return boolean
	 * @date: 2017-6-13
	 */
	boolean getIsAll() {
		boolean isAll = false;

		int sel = 0;// 有选择
		int unsel = 0;// 未选择
		for (CompanyBean companyBean : dataList) {
			if (companyBean.getIsCheck()) {
				sel++;
			} else {
				unsel++;
			}
		}
		if (sel == 0 && unsel == 0) {
			// 全部没有选择的话
			isAll = true;
		} else if (sel > 0 && unsel == 0) {
			// 子项全部选择，这时要反选
			isAll = false;
		} else if (sel == 0 && unsel > 0) {
			// 子项全部没选
			isAll = true;
		} else {
			// 子项有部分选，有部分没选的时候
			isAll = true;
		}

		return isAll;
	}

	void saveIds(String id) {
		if (!idsList.contains(id)) {
			idsList.add(id);
		} else {
			idsList.remove(id);
		}
		// Log.e(TAG, idsList.toString());
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch, R.id.tvAll, R.id.tvAdd })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
		case R.id.tvSearch:
			finish();
			break;
		case R.id.tvAll:
			// 全选或者反选
			allSelect();
			break;
		case R.id.tvAdd:
			if (idsList.size() <= 0) {
				ToastUtil.getInstances().showMsg("请先选择业主");
				return;
			}
			// 纳入管辖
			saveOwner(supervision_id);
			break;
		default:
			break;
		}
	}
	
	void saveOwner(String super_id) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		StringBuilder sbBuilder = new StringBuilder();
		for (int i = 0; i < idsList.size(); i++) {
			sbBuilder.append(idsList.get(i));
			sbBuilder.append(",");
		}

		String userList = SysUtils.SbToString(sbBuilder);

		if (!TextUtils.isEmpty(userList)) {
			params.put("str", userList);
		}

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this,
				WebApi.SUPERVISION_OWNER_ADD, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								List<CompanyBean> temp = new ArrayList<CompanyBean>();
								for (int i = 0; i < dataList.size(); i++) {
									if (dataList.get(i).getIsCheck()) {
										temp.add(dataList.get(i));
									}
								}

								EventBus.getDefault().post(
										new SupervisionOwnerEvent(2,temp));

								finish();
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
}
